<template>
	<view class="member-center-page">
		<view class="top">
			<view class="user-card">
				<view class="child-info">
					<image style="width: 40px; height: 40px;"  :src="selectedStudent.imageUrl" round />
					<view class="name-time">
						<view class="name">{{selectedStudent.name}}</view>
						<view class="time"><view class="vip">vip</view>{{ selectedStudent.expireDate}} 到期</view>		
					</view>					
				</view>
				<view class="selecte-child-device" @click="selectOpenChildren">
					选择小孩设备
					<image style="width: 14px; height: 14px;"  src="/static/icon/arrow-right-member.png"  />
				</view>
			</view>
		</view>
		<view class="member-content">
			<view class="member-top-raduis"></view>
			<view class="member-card-list">
					<view class="member-card" :class="{'activeCard': current?.id === c.id} " v-for="(c, i) in payComboList" :key="c.id" @click="() => onSelectCard(c)">
						<view class="active-icon" v-if="current?.id=== c.id">
							<image  style="width: 52px; height: 18px;" src="/static/icon/preferential.png" />
						</view>
						<view class="name">{{c.name}}</view>
						<view class="preic">
							￥ {{ c.price }}
						</view>
						<view class="discount">
							折扣前
						  <view class="discount-count">￥{{ c.discountBeforePrice}}</view>
						</view>
					</view>
			</view>
		</view>

		<view class="pay-methods">
			<view class="title">支付方式</view>
			<view class="cell">
				<uni-data-checkbox @change="onChangePay" v-model="radioValue" :localdata="payMethod" selectedColor="#2BC888" selectedTextColor="#2BC888">
					
				</uni-data-checkbox>
				
				<view class="weixin-icon">
					<image src="/static/icon/wx-pay.png" style="width: 20px;height: 20px;"/>
				</view>
				
				
			
			 </view>
		</view>
		
		<view class="memmber-center-foolter">
			<button class="open-member-ship-btn"  @click="activateMembership">开通会员</button>
		</view>
		<view class="arg-tips">如开通， 则代表您同意 <view class="arg" @click="jumpArgPage">《会员服务协议》</view></view>
		<ActionSheet
		  title="请选择孩子"
		  v-if="show"
		  :show="show"
		  :actions="actions"
		  @close="onClose"
		  @select="onSelect"
		  @cancel="cancel"
		  cancel-text="取消"
		/>
		
	</view>
</template>

<script lang="ts" setup>
	import { computed, onMounted, ref } from 'vue'
	import { memberServer } from '@/common/index';
	import ActionSheet from "@/components/actionSheet/index.vue"
	import { useStudentListStore } from "@/stores/useStudentList.js"
	import { onLoad } from "@dcloudio/uni-app"
	import { global } from "@/utils/index"
	import { useBound } from "@/hooks/useBound.ts"
	const {tipBoundStudent, studentIsEmpt} = useBound();
	const studentStore = useStudentListStore();
	// const currentStudent = computed(() => studentStore.currentStudent)
	const allStud  = computed(() => studentStore.students)
	
	const payMethod = ref([
		{
			text:"微信",
			value:1
		}
	])
	
	const show = ref(false);
	const actions = allStud.value?.map(item => {
		return {
			...item,
			subname: `vip 到期时间 ${item.expireDate}`,
			color: '#07c160'
		}
	});
	const onSelect = ({id}) => {
		// studentStore.onselectStudent(detail);
		selectedStudent.value = allStud.value?.find(c => c.id === id)
		show.value = false
	}
	
	const selectedStudent = ref({}); // 当前显示学生，也是要充值的学生
	onLoad(({studentId}) => {
		if(studentId){ // 从学生管理跳转过来的
			selectedStudent.value = allStud.value?.find(c => c.id === studentId)
		} else { // 从个人中心直接点击过来的 
			selectedStudent.value = studentStore.currentStudent
		}
	})
		
	const payComboList = ref([]); // 充值价格列表
	
	const queryUnit = (unit: string | number) => {
		const u = Number(unit)
		// 时长单位【1-年，2-月，3-周，5-日】
		const t = [
			{
				label: '年',
				value: 1
			},
			{
				label: '月',
				value: 2
			},
			{
				label: '周',
				value: 3
			},
			{
				label: '日',
				value: 5
			}
		];
		const { label = ""} = t.find(item => item.value === u);
		return label;
	}
	const current= ref({});
	const onSelectCard = (id: string | number) => {
		current.value = id
	}
	const payCombos = async () => {
		try{
			const {status, data} = await memberServer.payCombos({type: '7'});
			if(status === '200'){
				console.log(data)
				payComboList.value = data;
				// 【ID1000077】会员中心的没有默认选中会员
				const c = data.find(item => Number(item.price) > 0.01 )
				current.value = c
			}
		}catch(e){
			console.log(e)
			//TODO handle the exception
		}
	}
	onMounted(() => {
		payCombos()
	})
	
	// 开通会员接口
	const submitOrderParent = async () => {
		const studentId = selectedStudent.value.id;
		const payComboId = current.value.id;
		if(studentId && payComboId){
			// const { openid } = JSON.parse(global.syncGetOpenIdByLocal());
			// console.log('openid---', openid)
			// if(!openid){
			// 	uni.showToast({
			// 		title:"支付失败---",
			// 		icon: 'none'
			// 	})
			// 	return;
			// }
			try{
				// console.log('开通参数', {studentId, payComboId, orderSource: 'app',orderType: 0, payChannel: 4, tradeType: 'JSAPI', wxOpenId: openid})
				// const {status, data} = await memberServer.miniappPay({studentId, payComboId, orderSource: 'app',orderType: 0, payChannel: 4, tradeType: 'JSAPI', wxOpenId: openid});
				const data = await memberServer.douyinPay({
					"orderSource": "wap", //固定的
					"payChannel": 5, //抖音支付=5
					"tradeType": "JSAPI", //固定的
					"orderType": 0, //固定的
					studentId,
					payComboId,
					channel:'',
					goodsTitle:current.value.name
				})
				const status = 13
				if(status === '200'){
					console.log('data', data)
					// const { appid, mch_id } = JSON.parse(data?.placeOrderJsonMsg)
					// const orderInfo = {
					// 	// partnerid: payParams.partnerid,
					// 	// prepayid: payParams.prepayid,
					// 	appid: appid,
					// 	timeStamp: data.timeStamp,   //  时间戳 (单位：秒)
					// 	nonceStr: data.nonceStr,     //  随机字符串
					// 	package: `prepay_id=${data.package}`,       //  固定值
					// 	signType: data.signType,     //  固定值
					// 	paySign: data.paySign,       //  签名
					// };
					// console.log('orderInfo-------->', orderInfo, mch_id)
					const { total_fee, mch_id} = JSON.parse(data.placeOrderJsonMsg);
					console.log('mch_id', mch_id)
					uni.requestPayment({
						provider:'wxpay',
						service:'5',
						getOrderStatus:(res) => {
							console.log('支付状态', res)
						},
						timeStamp: data.timeStamp,
						nonceStr: data.nonceStr,
						package: data.package,
						signType: data.signType,
						paySign: data.paySign,
						// orderInfo: payComboId,
						success(res) {
							console.log("支付成功", res)
							uni.showToast({
								title:"支付成功",
								duration:2000,
								icon:"success",
								success() {
									setTimeout(() => {
										uni.switchTab({
											url:"/pages/tabbar/mine/index"
										})
									}, 1000)
								}
							})
						},
						fail(res) {
							console.log("支付失败", res)
						}
					})
					
					// todo https://developers.weixin.qq.com/community/develop/doc/000e8aab8d4770b6ca11c03ea6b800
					// uni.showToast({
					// 	icon:'success',
					// 	title:"支付成功",
					// 	success() {
					// 		uni.requestPayment({
					// 			provider:'wxpay',     //  支付类型 - 固定值
					// 			timeStamp: data.timestamp,   //  时间戳 (单位：秒)
					// 			nonceStr: data.noncestr,     //  随机字符串
					// 			package: data.package,       //  固定值
					// 			signType: data.signType,     //  固定值
					// 			paySign : data.sign,       //  签名
					// 			success: (res)=>{
					// 				console.log('success:' + JSON.stringify(res));
					// 				uni.showToast({
					// 					title:"支付成功",
					// 					icon:"success",
					// 					duration:2000,
					// 					success() {
					// 						setTimeout(() => {
					// 							uni.switchTab({
					// 								url:"/pages/tabbar/mine/index"
					// 							})
					// 						}, 3000)
					// 					}
					// 				})
					// 			},
					// 			fail: (err)=>{
					// 				console.log('fail:' + JSON.stringify(err));
					// 				uni.showToast({
					// 					icon: 'none',
					// 					title: '支付失败'
					// 				})
					// 			}
					// 		});
					// 	}
					// })
				}
			}catch(e){
				console.log(e)
				//TODO handle the exception
			}
		} else {
			console.log('学生id,或者套餐id 错误', studentId, payComboId)
		}
	}
	const activateMembership = () => {
		console.log('当前选择', current.value)
		uni.showModal({
			title:"支付提示",
			content:'请您去应用商店下载"家长守护助手-手机放沉迷"APP 进行购买支付'
		})
		return
		if(studentIsEmpt.value){
			tipBoundStudent();
			return;
		}
		
		if( !current.value?.id){
			uni.showToast({
				title:"请选择包月或包年",
				icon:'none'
			})
			return;
		}
		
		if(selectedStudent.value?.name){
			uni.showModal({
				title:"开通会员",
				content:`确认为${selectedStudent.value?.name}开通包${queryUnit(current.value?.unit)}为${current.value?.price}的会员吗`,
				cancelText:"取消",
				confirmText:"开通",
				success({confirm}) {
					if(confirm){
						console.log('开通')
						submitOrderParent();
					}
				}
			})
		}
	}
	
	const radioValue = ref(1);
	const onChangePay = ({detail}) => {
		radioValue.value = detail;
	}
	
	const selectOpenChildren = () => {
		show.value = true
	}
	const onClose = () => {
		show.value = false
	}
	const cancel= () => {
		show.value = false
	}
	
	
	const jumpArgPage = () => {
		uni.navigateTo({
			url:"/pagesC/memberAgreement/index"
		})
	}
	
</script>

<style lang="scss">
	page{
		background-color: #f7fbfe;
	}
</style>
<style scoped lang="scss">
	.member-center-page{
		background-color: #f7fbfe;
		.top{
			background-color: #404b72;
			width: 100%;
			height: 300upx;
			position: relative;
			.user-card{
				position: absolute;
				bottom: 0;
				left: 0;
				right: 0;
				margin: auto;
				width: 85%;
				padding:30upx;
				background: linear-gradient( 270deg, #FBD5B6 0%, #F1B583 100%);
				border-top-left-radius: 16upx;
				border-top-right-radius: 16upx;
				display: flex;
				justify-content: space-between;
				align-items: center;
		
				.child-info{
					display: flex;
					justify-content: space-between;
					align-items: center;
					.name-time{
						display: flex;
						flex-direction: column;
						justify-content: space-between;
						align-items: flex-start;
						margin-left: 20upx;
						.name{
							font-weight: 800;
							font-size: 32upx;
							color: #343C5C;
						}
						.time{
							margin-top: 20upx;
							display: flex;
							justify-content: flex-start;
							align-items:center;
							font-weight: 400;
							font-size: 20upx;
							color: #8b7977;
							.vip{
								margin-right: 10upx;
							}
						}
					}
				}
			}
			.selecte-child-device{
				display: flex;
				justify-content: center;
				align-items: center;
				padding: 10upx 20upx;
				border-radius: 40upx;
				background-color: #f9d5b8;
				border: 1px solid  rgba(255,255,255,0.2);
				font-weight: 400;
				font-size: 24upx;
				color: #54556b;
			}
		}
	
		.member-content{
			background-color: #f7fbfe;
			padding: 0 20upx 20upx 20upx;
			border-top-left-radius: 16upx;
			border-top-right-radius: 16upx;
			.member-top-raduis{
				width: 100%;
				height: 100upx;
				border-top-left-radius: 16upx;
				border-top-right-radius: 16upx;
				background: linear-gradient(#fcf5ee 0%, #fbfdfe 100%);
			}
			.member-card-list{
				display: flex;
				justify-content: space-between;
				align-items: center;
				width: 100%;
				flex-wrap: wrap;
				.member-card{
					min-width: 32%;
					height: 300upx;
					background: #FFFFFF;
					box-shadow: 0px 4upx 10upx 0px rgba(222,229,235,0.2);
					border-radius: 24upx;
					display: flex;
					flex-direction: column;
					align-items: center;
					justify-content: center;
					margin-bottom: 40upx;
					.name{
						font-weight: 400;
						font-size: 28upx;
						color: #343C5C;
					}
					.preic{
						font-weight: bold;
						font-size: 60upx;
						color: #343C5C;
						margin-top: 20upx;
						margin-bottom: 20upx;
					}
					.discount{
						display: flex;
						flex-direction: column;
						align-items: center;
						justify-content: center;
						font-weight: 400;
						font-size: 24upx;
						color: #AAACB8;
						.discount-count{
							text-decoration: #AAACB8;
							margin-top: 10upx;
						}
					}
				}
				.activeCard{
					box-sizing: border-box;
					border:2px solid #f6c49c;
					background-color: #fff8f2;
					position: relative;
					box-sizing: border-box;
					.active-icon{
						position: absolute;
						top: -4upx;
						right:-4upx;
					}
				}
			}
		}
		
		
		
		.pay-methods{
			margin-top: 80upx;
			padding: 30upx 30upx 100upx 30upx;
			// width: 100%;
			background: #FFFFFF;
			border-radius: 16upx;
			.title{
				font-weight: 800;
				font-size: 32upx;
				color: #333333;
				margin-bottom: 60upx;
			}
			.cell{
				.inline{
					display: flex;
					justify-content: flex-start;
					align-items: center;
					.van-cell-text{
						margin-left: 10upx;
					}
				}
				
			}
		}
		
		
		.arg-tips{
			position: fixed;
			left:0;
			right: 0;
			bottom: 36upx;
			margin: auto;
			display: flex;
			justify-content: center;
			align-items: center;
			font-size: 23upx;
			color: #AAACB8;
			.arg{
				color: #2BC888;
			}
		}
	}
	
</style>

<style lang="scss">
	.memmber-center-foolter{
		width: calc(100% - 200upx);
		margin-top: 120upx;
		margin: 0 auto;
		padding-bottom: 130upx;
		.van-button{
			
		}
		
		.scroll-view_H{
			white-space: nowrap;
			display: flex;
			justify-content: space-between;
			align-items: center;
		    min-width: 100%;
		}
	}
	
	.open-member-ship-btn{
		margin-top: 130upx;
		width: 100%;
		height: 80upx;
		background: linear-gradient( 270deg, #FBD5B6 0%, #F1B583 100%);
		border-radius: 80upx 80upx 80upx 80upx;
		font-weight: 800;
		font-size: 32upx;
		color: #343C5C;
		border:none;
	}
	.cell{
		display: flex;
		align-items: center;
		justify-content: space-between;
	}
</style>